<?php


namespace app\controller\admin;


use app\common\exception\ApiException;
use app\model\config\CouponModel;
use app\model\user\UserCouponModel;
use app\model\user\UserModel;
use app\service\user\UserCouponService;
use think\facade\Db;

class CouponController extends BaseAdminController
{
    function setModel()
    {
        return new CouponModel();
    }

    function setWithModel()
    {
        // TODO: Implement setWithModel() method.
    }

    function setSearch()
    {
        // TODO: Implement setSearch() method.
    }

    function setSort()
    {
        // TODO: Implement setSort() method.
    }

    public function save()
    {
        Db::startTrans();
        try {
            $data = $this->request->only(['id', 'coupon_name', 'use_type', 'amount', 'use_end_time', 'type', 'mobile', 'status']);

            $id = $data['id'] ?? 0;

            if (!$id) {
                $model = clone $this->setModel();
                $model->save($data);
                $id = $model->id;
            } else {
                $model = $this->setModel()->where('id', $id)->find();
                $model->save($data);
            }
            if ($data['type'] == 1 && isset($data['mobile'])) {
                $mobileArr = explode(',', $data['mobile']);
                $userIdArr = UserModel::whereIn('mobile', $mobileArr)->column('id');
                if (!$userIdArr) {
                    throw new ApiException('发放的用户不存在');
                }
                $userCouponService = new UserCouponService();
                $userCouponService->sendCouponToUserArr($userIdArr, $id);
            }
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception);
        }
    }

    /**
     * 优惠券发放记录
     * @return \think\response\Json
     */
    public function record()
    {
        try {
            $where = [];
            $id = $this->request->param('id', '', 'trim');
            $where[] = ['coupon_id', '=', $id];
            $search = $this->request->param('search', '', 'trim');
            if ($search != '') {
                $userIdArr = UserModel::where('nick|mobile', 'like', '%' . $search . '%')->column('id');
                $where[] = ['user_id', 'in', $userIdArr];
            }
            $status = $this->request->param('status', '', 'trim');
            if ($status != '') {
                $where[] = ['is_used', '=', $status];
            }
            $list = UserCouponModel::where($where)
                ->order('id', 'desc')
                ->paginate(['list_rows' => $this->limit, 'page' => $this->page])
                ->toArray();
            foreach ($list['data'] as &$v) {
                $userInfo = UserModel::find($v['user_id']);
                $v['avatar'] = $userInfo['avatar'] ?? '';
                $v['nick'] = $userInfo['username'] ?? '';
                $v['mobile'] = $userInfo['mobile'] ?? '';
            }
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }
}